//
//  JEmotionKeyboardVC.swift
//  01-表情键盘
//
//  Created by Jason on 29/5/15.
//  Copyright (c) 2015 Shepherd. All rights reserved.
//

import UIKit
private let reuseId = "JEmotionKeyboardVC" 
// 整个自定义键盘包含两个部分:UICollectionView + ToolBar
class JEmotionKeyboardVC: UIViewController {
    // 选中表情的回调闭包
    var selectedEmoticons:((emoticons:JEmoticons)->())?
    /// 实例化键盘控制器,并且选中指定表情的回调
    init(selectedEmoticons:(emoticons:JEmoticons)->()) {
        super.init(nibName: nil, bundle: nil)
        // 记录闭包
        self.selectedEmoticons = selectedEmoticons
    }
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    /// 表情数组
    lazy var emotionList: [JEmoticons] = {
       return JEmoticons.emoticonList()
    }()
    lazy var toolBar : UIToolbar = {
       let tool = UIToolbar(frame: CGRectZero)
       // 初始化临时的可变数组
       var items = [AnyObject]()
       var index = 0
       for str in ["默认","最近","emoji","浪小花"] {
            let item = UIBarButtonItem(title: str, style: UIBarButtonItemStyle.Plain, target: self, action: "selectItem:")
            items.append(item)
            item.tag = index
            if index++ < 3 {
                let flexItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
                items.append(flexItem)
            }
       }
       // 引用传递
       tool.items = items
       tool.tintColor = UIColor.darkGrayColor()
       return tool
    }()
    // 重写loadView方法 纯代码开发时需要
    override func loadView() {
        super.loadView()
        setupUI()
        // 设置自动布局 关闭Autoresizing
        toolBar.setTranslatesAutoresizingMaskIntoConstraints(false)
        collectionView.setTranslatesAutoresizingMaskIntoConstraints(false)
        
        var cons = [AnyObject]()
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["cv":collectionView])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["toolBar":toolBar])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[toolBar(44)]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["cv":collectionView,"toolBar":toolBar])
        view.addConstraints(cons)
    }
    // 设置视图
    private func setupUI() {
        view.addSubview(toolBar)
        view.addSubview(collectionView)
    }
    // 懒加载表情键盘的UICollectionView的部分
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
        let w = UIScreen.mainScreen().bounds.width / 7
        layout.itemSize = CGSizeMake(w, w)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.sectionInset = UIEdgeInsetsMake(4, 0, 0, 0)
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal

        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        cv.dataSource = self
        cv.delegate = self
        cv.pagingEnabled = true
        cv.backgroundColor = UIColor.whiteColor()
        cv.showsHorizontalScrollIndicator = false
        cv.registerClass(JEmotionCell.self, forCellWithReuseIdentifier: reuseId)
        return cv
    }()
    
    /** 具体选中哪个UIBarButtonItem */
    func selectItem(item:UIBarButtonItem) {
        var index = 0
        switch item.tag {
        case 1: index = 1
        case 2: index = 7
        case 3: index = 11
        default:index = 0
        }
        let indexPath = NSIndexPath(forItem: index * 21, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.redColor()
    }
}

extension JEmotionKeyboardVC : UICollectionViewDataSource,UICollectionViewDelegate {
    // MARK: - UICollectionView的delegate方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 根据indexPath得到用户选中的表情
        if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? JEmotionCell {
            // 闭包回调
            selectedEmoticons!(emoticons:cell.emotions!)
        }
    }
    // MARK: - UICollectionView的dataSource方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emotionList.count
    }
    //
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseId, forIndexPath: indexPath) as! JEmotionCell
        cell.emotions = emotionList[indexPath.item]
        return cell
    }
}
// 自定义cell
class JEmotionCell : UICollectionViewCell {
    // 模型数据
    var emotions : JEmoticons?{
        didSet {
            // 1.设置图像
            if emotions?.imgPath != nil {
                emotionBtn.setImage(UIImage(contentsOfFile: emotions!.imgPath!), forState: UIControlState.Normal)
            } else {
                emotionBtn.setImage(nil, forState: UIControlState.Normal)
            }
            // 2.设置emoji
            emotionBtn.setTitle(emotions?.emojiStr ?? "", forState: UIControlState.Normal)
            
            // 3.删除按钮
            if emotions!.removeFlag {
                emotionBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emotionBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    var emotionBtn = UIButton()
    // 初始化方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        emotionBtn.frame = CGRectInset(bounds, 4, 4)
        emotionBtn.backgroundColor = UIColor.whiteColor()
        // 取消button的可交互属性,让代理可以执行
        emotionBtn.userInteractionEnabled = false
        // 指定文本与图片的大小一致
        emotionBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        addSubview(emotionBtn)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

